/**
 * @author:albert
 */

package com.bkbw.live.battle.business.ai;

import java.util.Iterator;
import java.util.LinkedList;

import com.bkbw.live.battle.business.UnitObject;

import com.badlogic.gdx.ai.msg.Telegram;


public class GoalComposite<EntityType extends UnitObject> extends Goal<EntityType> {
	
	protected LinkedList<Goal<EntityType>> subgoalList;

	public GoalComposite(EntityType entity) {
		super(entity);
	}
	
	protected Goal.Status processSubgoals() {
		Iterator<Goal<EntityType>> iterator = subgoalList.iterator();
		while (iterator.hasNext()) {
			Goal<EntityType> goal = iterator.next();
			if (goal.isComplete() || goal.isFailed()) {
				goal.terminate();
				iterator.remove();
			}
		}
		
		if (subgoalList.size() != 0) {
			Status subgoalStatus = subgoalList.getFirst().process();
			if (subgoalStatus == Status.Completed && subgoalList.size() > 1) {
				return Status.Active;
			}
			return subgoalStatus;
		}
		else {
			return Status.Completed;
		}
	}
	
	protected boolean forwardMessageToFrontMostSubgoal(Telegram msg){
		if (subgoalList.size() != 0) {
			return subgoalList.getFirst().handleMessage(msg);
		}
		return false;
	}
	
	@Override
	public boolean handleMessage(Telegram msg) {
		return forwardMessageToFrontMostSubgoal(msg);
	}
	
	@Override
	public void addSubgoal(Goal<EntityType> goal) {
		subgoalList.add(goal);
	}
	
	public void removeAllSubgoals() {
		for (Goal<EntityType> goal : subgoalList) {
			goal.terminate();
		}
		subgoalList.clear();
	}
}
